/*
 * @Description:子表单组件
 * @Author: LCL
 * @Date: 2021-11-17
 * @LastEditors: LCL
 * @LastEditTime: 2021-12-10
 * @FilePath: /beff/src/components/SubForm/index.tsx
 */
import { MenuOutlined } from '@ant-design/icons';
import { Button, Form, Input, Tooltip, Select, DatePicker } from 'antd';
import type { StoreValue } from 'rc-field-form/lib/interface';

import React from 'react';

import styles from './index.less';

type SubFormProps = {
  // form: FormInstance;
  subFormObj: any;
  onSubFormChange: Function;
};

const SubForm: React.FC<SubFormProps> = (props) => {
  const { subFormObj } = props;
  const [form] = Form.useForm();

  // 初始值，到时根据modal数据获取，默认可展示1条
  const initialValue = subFormObj.children.map((item) => {
    const obj = {};
    item.forEach((formItem) => {
      obj[formItem.field] = formItem.value;
    });
    return obj;
  });
  // const initialValue = [];

  // 子表单内组件类型
  const componentList = {
    input: Input,
    textarea: Input.TextArea,
    select: Select,
    datePicker: DatePicker,
    dateRange: DatePicker.RangePicker,
  };

  // 组件的宽度，默认为150，如有特殊的在此添加
  // const widthObj = {
  //   textarea: 310,
  //   dateRange: 310,
  // };

  const getTotalWidth = () => {
    const totalWidth = subFormObj.children[0].reduce((preValue, currentValue) => {
      // const componentProps = currentValue.props;
      // let type = currentValue.name;
      // if (currentValue.name === 'input' && componentProps.textarea) {
      //   type = 'textarea';
      // }
      const width = currentValue.subFormCompWidth;
      return width + 10 + preValue; // 10是padding值
    }, 120);
    return totalWidth;
  };
  const totalWidth = getTotalWidth();
  /**
   * @description: 获取操作列表list
   */
  const getMenu = (
    add: (defaultValue?: StoreValue, insertIndex?: number) => void,
    remove: (index: number | number[]) => void,
    name: number,
  ) => {
    const handleClick = (e) => {
      const type = e.target.dataset.type;
      if (type === 'copy-next') {
        const subFormList = form.getFieldValue(subFormObj.field);
        add(subFormList[name], name + 1);
        console.log('复制到下一行');
      }
      if (type === 'copy-bottom') {
        const subFormList = form.getFieldValue(subFormObj.field);
        add(subFormList[name], subFormList.length);
        console.log('复制到最后一行');
      }
      if (type === 'insert-last') {
        console.log('向上插入行');
        add({}, name);
      }
      if (type === 'insert-next') {
        console.log('向下插入行');
        add({}, name + 1);
      }
      if (type === 'delete') {
        console.log('删除');
        remove(name);
      }
    };
    const ul = (
      <ul className={styles.menu} onClick={handleClick}>
        <li className={styles.menuItem} data-type="copy-next">
          复制到下一行
        </li>
        <li className={styles.menuItem} data-type="copy-bottom">
          复制到最后一行
        </li>
        <li className={styles.menuItem} data-type="insert-last">
          向上插入行
        </li>
        <li className={styles.menuItem} data-type="insert-next">
          向下插入行
        </li>
        <li className={styles.menuItem} data-type="delete">
          删除
        </li>
      </ul>
    );

    return ul;
  };

  const onValuesChange = (changeVal, allVal) => {
    const children = allVal[subFormObj.field].map((item) => {
      const list = [...subFormObj.children[0]];
      const arr = list.map((formItem) => {
        const tempItem = JSON.parse(JSON.stringify(formItem));
        tempItem.value = item[formItem.field] || null;
        return tempItem;
      });
      return arr;
    });
    // console.log('subform children:',children);
    props.onSubFormChange(children);
  };
  if (subFormObj.children[0].length > 0) {
    return (
      <div style={{ width: '100%' }} className={styles.wrapper}>
        <div className={styles.subFormHead} style={{ width: totalWidth }}>
          <div
            className={styles.headItem}
            style={{
              width: 60,
              position: 'sticky',
              left: 0,
              zIndex: 2,
              background: '#f4f4f4',
              borderBottom: '1px solid #efefef',
            }}
          >
            序号
          </div>
          {subFormObj.children[0].map((item, index, arr) => {
            const width = item.subFormCompWidth + 10;
            let style: any = { width };
            // 固定列逻辑
            if (subFormObj.stickyColumn.enable && index < subFormObj.stickyColumn.limit) {
              let lastWidth = 60;
              if (index > 0) {
                for (let i = 1; i <= index; i += 1) {
                  const tempWidth = arr[i - 1].subFormCompWidth + 10;
                  lastWidth += tempWidth;
                }
              }

              style = {
                ...style,
                position: 'sticky',
                left: lastWidth,
                zIndex: 2,
                background: '#f4f4f4',
              };
            }
            return (
              <div key={item.id} className={styles.headItem} style={style}>
                {item.title}
              </div>
            );
          })}
          <div className={styles.operate}>操作</div>
        </div>
        <Form form={form} onValuesChange={onValuesChange} preserve={false}>
          <Form.List name={subFormObj.field} initialValue={initialValue}>
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, fieldKey, ...restField }, index) => (
                  <div key={key} className={styles.rowList} style={{ width: totalWidth }}>
                    <div className={styles.rowHead}>{index + 1}</div>
                    {subFormObj.children[0].map((componentItem, componentIndex, arr) => {
                      let style = {};
                      const { id } = componentItem;
                      const componentProps = componentItem.props;
                      let type = componentItem.name;
                      if (componentItem.name === 'input' && componentProps.textarea) {
                        type = 'textarea';
                      }
                      const Tag = componentList[type];
                      const width = componentItem.subFormCompWidth;

                      // 固定列逻辑
                      if (
                        subFormObj.stickyColumn.enable &&
                        componentIndex < subFormObj.stickyColumn.limit
                      ) {
                        let lastWidth = 60;
                        if (componentIndex > 0) {
                          for (let i = 1; i <= componentIndex; i += 1) {
                            const tempWidth = arr[i - 1].subFormCompWidth + 10;
                            lastWidth += tempWidth;
                            console.log(lastWidth);
                          }
                        }
                        style = {
                          position: 'sticky',
                          left: lastWidth,
                          zIndex: 2,
                          background: '#fff',
                          borderBottom: '1px solid #e2e2e2',
                        };
                      }
                      return (
                        <div className={styles.rowItem} key={componentItem.id} style={style}>
                          <Form.Item
                            {...restField}
                            className={styles.noMargin}
                            name={[name, `${id}`]}
                            fieldKey={[fieldKey, `${id}`]}
                          >
                            <Tag {...componentProps} style={{ width: width }} />
                          </Form.Item>
                        </div>
                      );
                    })}

                    <Tooltip title={getMenu(add, remove, name)} color="white">
                      <div className={styles.operate}>
                        <MenuOutlined style={{ color: '#4aa5fe', fontSize: 16 }} />
                      </div>
                    </Tooltip>
                  </div>
                ))}
                <Button className={styles.add} type="dashed" onClick={() => add({})}>
                  添加
                </Button>
              </>
            )}
          </Form.List>
        </Form>
      </div>
    );
  }
  return <div>请添加子字段</div>;
};

export default SubForm;
